# coding: utf-8

from colorHash import *
from dao import DAO


def kNN(fn, k=10, distance=17):
    hash = color_hash(Image.open(fn))
    knn = sorted(mhashKNN(hash, distance=distance), key=lambda x: x[1])
    return knn[:k]


def hashKNN(hash, distance=17):
    for doc in DAO.find():  # mongodb
        dist = hash - hex_to_hash(doc["hash"])
        if dist <= distance:
            yield doc["name"], dist


def _hashKNN(hdd):
    hash, doc, distance = hdd
    dist = hash - hex_to_hash(doc["hash"])
    if dist <= distance:
        return doc["name"], dist
    else:
        return None

def mhashKNN(hash, distance=17):
    import multiprocessing
    pool = multiprocessing.Pool(18)

    def getData(hash, distance):
        for doc in DAO.find():  #  mongodb
            yield hash, doc, distance

    ## results = pool.map(_hashKNN, getData(hash, docs, distance))
    ## # pool.close()
    ## # pool.join()
    ## for result in results:
    ##     if result:
    ##         yield result[0]
    results = pool.map_async(_hashKNN, getData(hash, distance))
    while not results.ready():
        pass
    for x in results.get():
        if x:
            yield x


